package com.swing.sky.system.framework.security.service;

import com.swing.sky.system.framework.security.exception.UserNotFoundException;
import com.swing.sky.system.framework.security.exception.UserUnUsedException;
import com.swing.sky.system.module.domain.SysUserDO;
import com.swing.sky.system.module.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserDetailsServiceImp implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImp.class);
    @Resource
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDO user = userService.getUserByUsername(username);
        if(user == null){
            log.info("the user:{ } doesn't exist ", username);
            try {
                throw new UserNotFoundException(username + "wrong user or password, try again.");
            } catch (UserNotFoundException e) {
                e.printStackTrace();
            }
        }
        if(!user.getUse()){
            log.info("this user:{ } has been forbidden.", username);
            try {
                throw new UserUnUsedException(username + "this user has been forbidden.");
            } catch (UserUnUsedException e) {
                e.printStackTrace();
            }
        }
        return new UserDetailsImp(user);
    }
}
